package com.cskaoyan.catmall.aspectj;

import com.cskaoyan.catmall.exception.ValidationException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;


/**
 * 创建日期: 2022-01-08-12-31
 * author : WQW
 * description: validated参数验证切面组件
 */


@Aspect
@Component
public class ValidatedAspect {


    /**
     * @param
     * @return void
     * @description 对controller包下的所有类中的方法做增强，进行参数验证
     * @author WQW
     * @date 2022/1/8 13:18
     */
    @Before("execution(* com.cskaoyan.catmall.controller..*.*(..))")
    public void validateBefore(JoinPoint joinPoint) throws ValidationException {
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof BindingResult) {
                if (((BindingResult) arg).hasFieldErrors()) {
                    BindingResult bindingResult = (BindingResult) arg;
                    FieldError fieldError = bindingResult.getFieldError();
                    String field = fieldError.getField(); //成员变量
                    Object rejectedValue = fieldError.getRejectedValue(); // 输入的值
                    String defaultMessage = fieldError.getDefaultMessage(); // 原因
                    throw new ValidationException(defaultMessage);
                }
            }
        }
    }
}
